package by.epam.trenings.vkphotorest.app;

import by.epam.trenings.vkphotorest.R;
import by.epam.trenings.vkphotorest.adapters.PhotoGridAdapter;
import by.epam.trenings.vkphotorest.content.contract.TaskContract;
import by.epam.trenings.vkphotorest.requests.PhotoRequestsBuilder;
import by.epam.trenings.vkphotorest.service.ApplicationService;
import by.epam.trenings.vkphotorest.service.ServiceCallbackListener;
import by.epam.trenings.vkphotorest.service.handlers.BaseHandler;
import by.epam.trenings.vkphotorest.service.handlers.impl.DbInsertHandler;
import by.epam.trenings.vkphotorest.utils.TaskApplication;
import android.os.Bundle;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class PhotoGridActivity extends FragmentActivity implements
		LoaderManager.LoaderCallbacks<Cursor>, ServiceCallbackListener,
		OnScrollListener {

	private ProgressBar mProgressBar;

	public static boolean sBusy = false;

	private GridView mGridView;

	public static final String EXTRA_PHOTO_POSITION = "position";

	private PhotoGridAdapter mGridAdapter;

	private String mAlbumId;

	private int LOADER_ID = 0;

	private int mRequestId;

	private Boolean mReloadDataOnCreate = true;

	private static final String EXTRA_IS_ORIENTATION_CHANGED = "mIsOrientationChanged";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photo_grid);

		mProgressBar = (ProgressBar) findViewById(R.id.activity_photo_grid_progress);
		mProgressBar.setVisibility(View.VISIBLE);

		if (savedInstanceState != null) {
			mReloadDataOnCreate = savedInstanceState
					.getBoolean(EXTRA_IS_ORIENTATION_CHANGED);
		}

		mGridView = (GridView) findViewById(R.id.activity_photo_grid_grid_view);
		mGridView.setOnScrollListener(this);

		Bundle extras = getIntent().getExtras();

		TextView albumName = (TextView) findViewById(R.id.activity_photo_grid_album_name);
		albumName.setText(extras.getString(AlbumsActivity.EXTRA_ALBUM_TITLE));
		albumName.setSelected(true);

		mAlbumId = extras.getString(AlbumsActivity.EXTRA_ALBUM_ID);

		if (mReloadDataOnCreate == true) {
			mRequestId = TaskApplication.getServiceHelper().deleteDatabase(
					TaskContract.PhotosColumns.CONTENT_URI, null, null);
		} else {
			Log.d("PGA", "screen orientation changed");
			mGridAdapter = new PhotoGridAdapter(getApplicationContext(), null);
			mGridView.setAdapter(mGridAdapter);
			getSupportLoaderManager().initLoader(LOADER_ID, null,
					PhotoGridActivity.this);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		TaskApplication.getServiceHelper().addListener(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		TaskApplication.getServiceHelper().removeListener(this);
		/*
		 * when i flingin screen then while flinging changing orientation of
		 * screen,image views still show Placeholder image( its means still
		 * flinging(sBusy == true)) thats why need sBusy = false;
		 */
		sBusy = false;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		mGridView.setVerticalScrollBarEnabled(false);
		outState.putBoolean(EXTRA_IS_ORIENTATION_CHANGED, mReloadDataOnCreate);
		super.onSaveInstanceState(outState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_photo_grid, menu);
		return true;
	}

	@Override
	public Loader<Cursor> onCreateLoader(int paramInt, Bundle paramBundle) {
		return new CursorLoader(this, TaskContract.PhotosColumns.CONTENT_URI,
				null, null, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> paramLoader, final Cursor cursor) {
		if (paramLoader.getId() == LOADER_ID) {
			if (cursor.getCount() != 0) {

				mGridView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View v,
							int position, long id) {

						Intent intent = new Intent(PhotoGridActivity.this,
								FullScreenPhotoActivity.class);
						intent.putExtra(EXTRA_PHOTO_POSITION, position);
						startActivity(intent);
					}
				});

				mGridAdapter.swapCursor(cursor);
			}
			// mReloadDataOnCreate = false; means that not reload data from
			// internet after first load
			mReloadDataOnCreate = false;
			mProgressBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> paramLoader) {
		mGridAdapter.swapCursor(null);
	}

	@Override
	public void onServiceCallback(int requestId, Intent requestIntent,
			int resultCode, Bundle data) {
		String action = requestIntent.getAction();
		if (resultCode == BaseHandler.FAILURE_RESPONSE
				&& mRequestId == requestId) {
			mProgressBar.setVisibility(View.GONE);
			Toast.makeText(PhotoGridActivity.this,
					data.getString(ApplicationService.ACTION_ON_ERROR),
					Toast.LENGTH_SHORT).show();
		} else if (ApplicationService.ACTION_DELETE.equals(action)
				&& mRequestId == requestId) {
			mRequestId = TaskApplication.getServiceHelper().insertDatabase(
					TaskContract.PhotosColumns.CONTENT_URI,
					PhotoRequestsBuilder.getAllAlbymPhotos(mAlbumId));
		} else if (ApplicationService.ACTION_INSERT.equals(action)
				&& mRequestId == requestId) {
			if (data.getInt(DbInsertHandler.EXTRA_CURSOR_COUNT) != 0) {
				mGridAdapter = new PhotoGridAdapter(getApplicationContext(),
						null);
				mGridView.setAdapter(mGridAdapter);
				getSupportLoaderManager().initLoader(LOADER_ID, null,
						PhotoGridActivity.this);
			} else {
				mProgressBar.setVisibility(View.GONE);
				String warning = getResources().getString(
						R.string.activity_photo_grid_strings_no_photo);
				Toast.makeText(PhotoGridActivity.this, warning,
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		switch (scrollState) {
		case OnScrollListener.SCROLL_STATE_IDLE:
			sBusy = false;
			int count = view.getChildCount();

			Boolean isNotifyed = false;

			for (int i = 0; i < count; i++) {
				if (view.getChildAt(i).getTag() != null && isNotifyed == false) {
					isNotifyed = true;
					mGridAdapter.notifyDataSetChanged();
				}
				view.getChildAt(i).setTag(null);
			}
			Log.d("PGA", "Idle");
			break;
		case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:

			sBusy = false;
			Log.d("PGA", "Touch scroll");
			break;
		case OnScrollListener.SCROLL_STATE_FLING:

			sBusy = true;
			Log.d("PGA", "Fling");
			break;
		}
	}
}
